import { Tabs, Flex, Divider, List, Skeleton, message } from "antd";
import { useEffect, useState, useRef } from "react";
import { items, TABS } from "./FXBaoGaoData";
import FXBaoGaoCard from "./FXBaoGaoCard";
import {
  PAGE_SIZE,
  SITES_URL,
  sortByOrder,
  processCurrentPage,
} from "../Common/commonData";
import InfiniteScroll from "react-infinite-scroll-component";
import { fxbaogao } from "@/servers/crawler";

export default function FXBaoGao({ initHotRankings }) {
  const [messageApi, contextHolder] = message.useMessage();
  const [tab, setTab] = useState("today");
  const onChange = (key) => {
    setTab(key);
  };
  const hotRankings = useRef(sortByOrder(initHotRankings));
  const [showHotRankings, setShowHotRankings] = useState(
    hotRankings.current.slice(0, PAGE_SIZE)
  );
  const isLoading = useRef(false);
  const scrollContainerRef = useRef(null);
  const cardRef = useRef(null);

  useEffect(() => {
    let isMounted = true;
    // 防止旧数据渲染
    setShowHotRankings([]);

    const fetchData = async () => {
      try {
        let newData;
        if (tab === TABS.today) {
          newData = await fxbaogao.getDaily();
        } else if (tab === TABS.theWeek) {
          newData = await fxbaogao.getWeekly();
        } else if (tab === TABS.theMonth) {
          newData = await fxbaogao.getMonthly();
        }
        sortByOrder(newData);
        // 阻止相同渲染
        if (newData === hotRankings.current) return;
        if (isMounted && newData) {
          hotRankings.current = newData;
          setShowHotRankings(hotRankings.current.slice(0, PAGE_SIZE));
        }
      } catch (error) {
        if (isMounted) {
          const errorMessage = {
            [TABS.today]: "日榜信息获取失败",
            [TABS.theWeek]: "周榜信息获取失败",
            [TABS.theMonth]: "月榜信息获取失败",
          }[tab];
          messageApi.error(errorMessage);
        }
      }
    };

    fetchData();

    return () => {
      isMounted = false;
    };
  }, [tab, messageApi]);

  const loaderMoreData = (pageSize = PAGE_SIZE) => {
    if (
      isLoading.current ||
      showHotRankings.length > hotRankings?.current.length
    )
      return;
    isLoading.current = true;

    const [currentPage, currentPageSize] = processCurrentPage(
      pageSize,
      hotRankings.current.length,
      hotRankings.current
    );

    // 获得剩余所有数据
    if (currentPageSize === hotRankings.current.length) {
      setShowHotRankings(hotRankings.current);
      return;
    }

    setShowHotRankings((prev) =>
      prev.concat(
        hotRankings.current.slice(
          showHotRankings.length,
          showHotRankings.length + currentPageSize
        )
      )
    );
    isLoading.current = false;
  };

  // 1. 监听窗口大小变化，并调整容器高度
  useEffect(() => {
    const handleResize = () => {
      if (isLoading.current) return;

      const windowHeight = window.innerHeight;
      const cardHeight = cardRef?.current?.clientHeight || 100;
      const containerHeight = cardHeight * showHotRankings?.length;
      const cardNum =
        Math.ceil((windowHeight - containerHeight) / cardHeight / 10) * 10;
      if (cardNum >= 10 && containerHeight < windowHeight) {
        loaderMoreData(cardNum);
      }
    };

    // 首次加载时执行
    handleResize();

    // 监听窗口变化
    window.addEventListener("resize", handleResize);

    // 组件卸载时移除监听
    return () => {
      window.removeEventListener("resize", handleResize);
    };
    // 依赖 hotRankings 确保数据更新后重新计算, 依赖isLoading否则会初始加载两次
  }, [isLoading.current, hotRankings.length]);

  return (
    <div ref={scrollContainerRef}>
      {contextHolder}
      <Divider style={{ margin: "0" }} />
      <Tabs
        defaultActiveKey="today"
        items={items}
        onChange={onChange}
        tabBarStyle={{
          margin: "0",
          paddingLeft: "1rem",
          borderRadius: "0.3rem 0.3rem 0 0",
          backgroundColor: "white",
          boxShadow:
            "rgba(0, 0, 0, 0.1) 0px 0px 5px 0px, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px",
        }}
      />
      <InfiniteScroll
        dataLength={showHotRankings.length}
        next={loaderMoreData}
        hasMore={showHotRankings.length < hotRankings.current.length}
        loader={
          <Skeleton
            avatar
            paragraph={{ rows: 1 }}
            active
            style={{ padding: 12 }}
          />
        }
        endMessage={
          <a target="_blank" href={SITES_URL.fxBaoGao}>
            <Divider plain>查看更多</Divider>
          </a>
        }
        scrollableTarget="scrollableDiv">
        <Flex vertical={true}>
          {showHotRankings.map((v, i) => (
            <div ref={i === 0 ? cardRef : null} key={tab + i}>
              <FXBaoGaoCard
                item={v}
                style={{
                  borderRadius: `${
                    i === showHotRankings.length - 1 && "0 0 0.3rem 0.3rem"
                  }`,
                }}
              />
              <Divider style={{ margin: "0" }} />
            </div>
          ))}
        </Flex>
      </InfiniteScroll>
    </div>
  );
}
